<template>
  <div>
    <el-form :model="basicInfo" label-width="100px">
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>基本信息</h4>
          <el-form-item label="分公司">
            <el-select v-model="showBranch" multiple :disabled="brachDisabled" style="width:220px">
              <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id.toString()" :label="item.branch_Name" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客资类型">
            <el-select v-model="basicInfo.usertype" multiple style="width:220px" :loading="customerTypeLoading" placeholder="客资类型">
              <!-- <el-option value="1" label="普通超市"></el-option> -->
              <el-option v-for="(item, index) in customerTypeList"
              :key="index"
              :label="item.name"
              :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="广告类型">
            <el-select v-model="basicInfo.markid" @change="markidChange" placeholder="广告类型" style="width:220px">
              <el-option v-for="(item, index) in markidGroup" :value="item.markId" :label="item.name" :key="index" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属设备">
            <el-checkbox-group  v-model="equipments" @change="checkBoxChange">
              <el-checkbox v-for="(item, index) in equipmentsGroup" :label = "item" :key="item">{{item}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="广告名称">
            <el-input v-model="basicInfo.cadname" placeholder="广告名称" style="width:220px"></el-input>
          </el-form-item>
          <el-form-item label="起止时间">
            <el-date-picker v-model="startStopTime" placeholder="起止时间" value-format="yyyy-MM-dd"
            type="daterange" @change="daterangeFormat" style="width:220px"></el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="basicInfo.cadmemo" type="textarea" placeholder="备注" style="width:220px"></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px" v-if="actionTag[0]">
        <div class="form-item" @click="divClick(0)">
          <h4>PC订货</h4>
          <el-form-item label="图片选择">
            <el-upload
              class="avatar-uploader"
              :action="url"
              name="imageFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.png">
              <img v-if="basicInfo.adPicture[0].adimage" :src="basicInfo.adPicture[0].adimage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转方式">
            <el-radio-group v-model="basicInfo.adPicture[0].actionId">
              <el-radio v-for="(item, index) in actionGroup[0]" :label="item.id.toString()">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="basicInfo.adPicture.actiontype !== '3'">
            <el-input v-model="basicInfo.adPicture[0].adurl" placeholder="请输入链接" style="width:220px"></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px" v-if="actionTag[1]">
        <div class="form-item" @click="divClick(1)">
          <h4>惠付通</h4>
          <el-form-item label="图片选择">
            <el-upload
              class="avatar-uploader"
              :action="url"
              name="imageFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.png">
              <img v-if="basicInfo.adPicture[1].adimage" :src="basicInfo.adPicture[1].adimage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转方式">
            <el-radio-group v-model="basicInfo.adPicture[1].actionId">
              <el-radio v-for="(item, index) in actionGroup[1]" :label="item.id.toString()">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="basicInfo.adPicture.actiontype !== '3'">
            <el-input v-model="basicInfo.adPicture[1].adurl" placeholder="请输入链接" style="width:220px"></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px" v-if="actionTag[2]">
        <div class="form-item" @click="divClick(2)">
          <h4>惠配通</h4>
          <el-form-item label="图片选择">
            <el-upload
              class="avatar-uploader"
              :action="url"
              name="imageFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept=".jpg,.png">
              <img v-if="basicInfo.adPicture[2].adimage" :src="basicInfo.adPicture[2].adimage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转方式">
            <el-radio-group v-model="basicInfo.adPicture[2].actionId">
              <el-radio v-for="(item, index) in actionGroup[2]" :label="item.id.toString()">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="basicInfo.adPicture.actiontype !== '3'">
            <el-input v-model="basicInfo.adPicture[2].adurl" placeholder="请输入链接" style="width:220px"></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div style="margin: 20px auto 20px;width:20%">
      <el-button @click="onSubmit(1, 'basicInfo')" type="success">提交</el-button>
      <el-button @click="onSubmit(2, 'basicInfo')" type="warning">暂存</el-button>
      <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { gggl, getInfo } from '../../../../../config/proxy.js'
  import { apiHost, apiURL } from '../../../../../config/settings.js'
  import mixins from '../../../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      return {
        basicInfo: {
          banchid: [], // 分公司
          usertype: [], // 客资类型
          markid: '', // 广告类型
          equipment: [], // 所属设备
          cadname: '', // 广告名称
          offlinetime: '', // 开始时间
          orderuptime: '', // 结束时间
          cadmemo: '', // 备注
          adPicture: [
            {
              actiontype: '', // 跳转方式
              actionName: '', // 跳转方式名称
              actionId: '', // 跳转id
              adimage: '', // 图片路径
              adurl: '', // 动作参数
              equipment: '1' // 所属设备
            },
            {
              actiontype: '', // 跳转方式
              actionName: '', // 跳转方式名称
              actionId: '', // 跳转id
              adimage: '', // 图片路径
              adurl: '', // 动作参数
              equipment: '2' // 所属设备
            },
            {
              actiontype: '', // 跳转方式
              actionName: '', // 跳转方式名称
              actionId: '', // 跳转id
              adimage: '', // 图片路径
              adurl: '', // 动作参数
              equipment: '3' // 所属设备
            }
          ]
        },
        equipments: [], // 所属设备中间变量
        equipmentsGroup: [], // 所属设备数组
        // radioModel: [], // radioModel
        showBranch: [],
        brachDisabled: false,
        customerTypeLoading: false, // 客资类型loading
        customerTypeList: [], // 客资类型数组
        markidGroup: [], // 广告类型数组
        actionGroup: [], // 跳转动作数组
        startStopTime: '', // 起止时间
        url: '', // 上传图片地址
        imageUrl: '', // 图片路径
        menuId: '',
        isCreateOrUpdate: '',
        detailData: [], // 详情
        tag: '',
        actionTag: [false, false, false]
      }
    },
    methods: {
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          // console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchAd () { // 查询广告
        var _data = {
          system: '1',
          ad: '2',
          page: 1,
          pageSize: 10000
        }
        gggl.mkgl.list(_data, (res) => { // 查询广告
          // console.log(res)
          if (res.message === 'ok') {
            this.markidGroup = res.content.content
            // this.equipmentsGroup = res.content.content[0].equipmentName.split(',')
            // console.log(this.equipmentsGroup)
          } else {
            this.message('查询失败', 'error')
          }
        })
      },
      markidChange (val) { // 广告类型切换
        console.log(val)
        if (val === '') {
          this.equipmentsGroup = []
          this.equipments = []
          this.basicInfo.equipment = []
        } else {
          for (let index = 0; index < this.markidGroup.length; index++) {
            const element = this.markidGroup[index]
            if (val === element.markId) {
              this.equipmentsGroup = this.strToArr(element.equipmentName)
              this.equipments = this.strToArr(element.equipmentName)
            }
          }
        }
        this.matchBusinessType()
      },
      checkBoxChange (val) { // 所属设备切换
        console.log(val)
        console.log(arguments)
        this.matchBusinessType()
      },
      matchBusinessType () { // 匹配 checkbox 数值
        var group = [
          {name: 'PC订货', value: '1'},
          {name: '惠付通', value: '2'},
          {name: '惠配通', value: '3'}
        ]
        var arr = []
        if (this.equipments.length > 0) {
          for (let i = 0; i < this.equipments.length; i++) {
            const checkEle = this.equipments[i]
            for (let k = 0; k < group.length; k++) {
              const allEle = group[k]
              if (checkEle === allEle.name) {
                arr.push(allEle.value)
              }
            }
          }
        }
        this.basicInfo.equipment = arr
        // console.log(this.basicInfo.equipment)
        this.searchAction(this.basicInfo.equipment)
      },
      searchAction (arr) { // 查询动作
        console.log(arr)
        this.actionGroup = []
        this.actionTag = [false, false, false]
        for (let index = 0; index < arr.length; index++) {
          const element = arr[index]
          var _data = {
            page: 1,
            pageSize: 10000,
            state: 1,
            system: 1,
            equipment: element
          }
          console.log(_data)
          gggl.dztzgl.list(_data, (res) => {
            console.log(res)
            // this.actionGroup[group[index].id] = res.content.content
            // this.actionGroup[index] = res.content.content
            Vue.set(this.actionGroup, element - 1, res.content.content)
          })
          this.actionTag[element - 1] = true
        }
        console.log(this.actionGroup)
        console.log(this.actionTag)
      },
      divClick (n) {
        this.tag = n
      },
      handleAvatarSuccess (res, file) { // 上传图片成功
        if (res.message === 'ok') {
          this.basicInfo.adPicture[this.tag].adimage = res.content.imageUrl
        } else {
          this.message('上传图片失败', 'error')
        }
      },
      beforeAvatarUpload (file) { // 上传图片之前
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!isLt3M) {
          this.$message.error('上传图片大小不能超过 3MB!')
        }
        return isLt3M
      },
      // radioChange (val, n) { // 跳转动作类型 切换
      //   console.log(arguments)
      //   for (let k = 0; k < this.actionGroup[n].length; k++) {
      //     const ele2 = this.actionGroup[n][k]
      //     if (val === ele2.id) {
      //       this.basicInfo.adPicture[n].actionName = ele2.name
      //       this.basicInfo.adPicture[n].actiontype = ele2.markId
      //     }
      //   }
      // },
      // matchActionId (detail) { // 根据动作markik 和 name 获取id
      //   console.log(detail)
      //   var self = this
      //   setTimeout(() => {
      //     console.log(self.actionGroup)
      //     for (let i = 0; i < self.actionGroup.length; i++) {
      //       var eleD = detail[i]
      //       if (self.actionGroup[i]) {
      //         var eleA = self.actionGroup[i]
      //         for (let k = 0; k < eleA.length; k++) {
      //           const eleAK = eleA[k]
      //           if (eleD.actionname !== '' && eleD.actiontype !== '') {
      //             console.log(eleAK)
      //             if (eleD.actionname === eleAK.name && eleD.actiontype === eleAK.markId) {
      //               // console.log('aa')
      //               // self.radioModel[i] = eleAK.id
      //               Vue.set(self.radioModel, i, eleAK.id)
      //             }
      //           }
      //         }
      //       }
      //     }
      //     console.log(self.radioModel)
      //   }, 300)
      // },
      searchDetail (row) { // 查询详情
        gggl.dhxtgl.banner.detail({id: row.cid}, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.detailData = res.content
            if (this.branchId === 1) {
              this.brachDisabled = false
              this.basicInfo.banchid = this.strToArr(res.content.branchIds)
              this.showBranch = this.strToArr(res.content.branchIds)
            } else {
              this.brachDisabled = true
              this.basicInfo.banchid.push(this.branchId)
              this.showBranch.push(this.branchName)
            }
            this.basicInfo.usertype = this.strToArr(res.content.usertype) // 客资类型
            this.basicInfo.markid = res.content.markid // 广告类型
            this.basicInfo.cadname = res.content.cadname // 广告名称
            this.basicInfo.offlinetime = this.timeDeltSecond(res.content.offlinetime) // 开始时间
            this.basicInfo.orderuptime = this.timeDeltSecond(res.content.orderuptime) // 结束时间
            this.startStopTime = [this.basicInfo.offlinetime, this.basicInfo.orderuptime]
            this.basicInfo.cadmemo = res.content.cadmemo // 备注
            // this.basicInfo.adPicture = res.content.detail // 图片路径
            Vue.set(this.basicInfo.adPicture, 0, res.content.detail[0])
            Vue.set(this.basicInfo.adPicture, 1, res.content.detail[1])
            Vue.set(this.basicInfo.adPicture, 2, res.content.detail[2])
            console.log(this.basicInfo.adPicture)
            // this.searchAction(this.strToArr(res.content.equipments))
            // this.matchActionId(res.content.detail) // 跳转方式
            var self = this
            setTimeout(() => {
              self.basicInfo.adPicture.adurl = res.content.adurl // 跳转参数
            }, 10)
            console.log(this.basicInfo)
          } else {
            this.message('查询详情失败', 'error')
          }
        })
      },
      onSubmit (type, formName) { // 创建
        console.log(arguments)
        var _data = this.basicInfo
        _data.banchid = this.branchId === 1 ? this.showBranch.join(',') : this.basicInfo.banchid[0]
        _data.usertype = _data.usertype.join(',')
        _data.createOrSave = type
        _data.createuser = this.userName
        _data.cid = this.isCreateOrUpdate === 'update' ? this.detailData.cid : ''
        console.log(_data)
        gggl.dhxtgl.banner[this.isCreateOrUpdate](_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.message('新增成功', 'success')
          } else {
            this.message('新增失败', 'error')
          }
          this.cancel(this.menuId)
        })
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      daterangeFormat (t) { // 时间段格式化
        this.basicInfo.orderuptime = t[0]
        this.basicInfo.offlinetime = t[1]
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      strToArr (str) { // 字符串数组转换
        var arr = []
        if (str.length > 1) {
          arr = str.split(',')
        } else {
          arr.push(str)
        }
        return arr
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    computed: {
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.dztzState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      }
    },
    watch: {
      update_state (curVal, oldVal) {  // 监听 更新状态 查询list
        this.searchList()
      }
    },
    created () {
      this.url = 'http://' + apiHost.newCms + ':20000' + apiURL.goodsSet_uploadImage
      this.searchAd()
      if (this.branchId === 1) {
        this.brachDisabled = false
        this.basicInfo.banchid.push(this.branchId.toString())
        this.showBranch.push(this.branchId.toString())
      } else {
        this.brachDisabled = true
        this.basicInfo.banchid.push(this.branchId.toString())
        this.showBranch.push(this.branchName)
      }
      this.menuId = this.$store.state.tab.menuId
      // console.log(this.$store.state.tab)
      if (this.$store.state.tab.uid) {
        this.isCreateOrUpdate = 'update'
        this.text = '编辑'
        this.searchCustomerType() // 查询客资类型
        // this.searchAction() // 查询动作
        this.searchDetail(this.$store.state.tab.uid)
      } else {
        this.isCreateOrUpdate = 'create'
        this.text = '新增'
        // this.searchAction() // 查询动作
        this.searchCustomerType() // 查询客资类型
      }
    }
  }
</script>
